package com.example.rfidwms;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zebra.rfid.api3.TagData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WriteTagActivity extends AppCompatActivity {

    public static Set<Integer> positionSet = new HashSet<>();
    public TextView statusTextViewRFID = null;
    RFIDHandler rfidHandler;
    private EditText editTextMName;
    private EditText editTextMClassifyNum;
    private EditText editTextMSpecs;
    private Button buttonMSearch;
    private recy_item_classify_Adapter recy_item_classify_adapter;
    private TextView editText2Tag;
    private TextView editTextWriteData;
    private Button buttonWrite;
    private Map<String, TagData> dataMap = new HashMap<>();
    private Application app = new Application();
    private FormBody formBody;
    //获取的json数据
    private String data;
    private String classify_num;
    private int id;
    private String name;
    private String specs;
    private String unit;
    private String epc;
    private RecyclerView recyclerview;
    private List<Map<String, Object>> list = new ArrayList<>();
    private boolean selectMode;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //添加分割线
                    recyclerview.addItemDecoration(new DividerItemDecoration(
                            WriteTagActivity.this, DividerItemDecoration.VERTICAL));
                    recy_item_classify_adapter = new recy_item_classify_Adapter(list, WriteTagActivity.this);

                    //设置布局显示格式
                    recyclerview.setLayoutManager(new LinearLayoutManager(WriteTagActivity.this));

                    recyclerview.setAdapter(recy_item_classify_adapter);
                    recy_item_classify_adapter.setOnItemClickListener(new recy_item_classify_Adapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            if (selectMode) {
                                // 如果当前处于多选状态，则进入多选状态的逻辑
                                // 维护当前已选的position
                                addOrRemove(position);
                            } else {
                                // 如果不是多选状态，则进入单选事件的业务逻辑
                                if (!positionSet.contains(position)) {
                                    // 选择不同的单位时取消之前选中的单位
                                    positionSet.clear();
                                }
                                addOrRemove(position);
//                                Toast.makeText(WriteTagActivity.this, list.get(position).get("id").toString(), Toast.LENGTH_SHORT).show();
                                //获取物资编码对应的epc
                                editTextWriteData.setText(list.get(position).get("epc").toString());
                            }
                        }
//多选监听
//                        @Override
//                        public void onItemLongClick(View view, int position) {
//                            if (!selectMode) {
//                                selectMode = true;
//                                positionSet.clear();
//                            }
//                        }
                    });
                    break;


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        防止布局被输入法顶出去
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_write_tag);

        statusTextViewRFID = findViewById(R.id.statusTextViewRFID);

        editTextMName = findViewById(R.id.editText_M_Name);
        editTextMClassifyNum = findViewById(R.id.editText_M_ClassifyNum);
        editTextMSpecs = findViewById(R.id.editText_M_Specs);
        buttonMSearch = findViewById(R.id.button_M_Search);
        recyclerview = findViewById(R.id.recy_M);
        editText2Tag = findViewById(R.id.editText_2Tag);
        editTextWriteData = findViewById(R.id.editText_writeData);
        buttonWrite = findViewById(R.id.button_write);

        // RFID Handler
        rfidHandler = new RFIDHandler();
        rfidHandler.onCreate(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        rfidHandler.onPause();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        String status = rfidHandler.onResume();
        statusTextViewRFID.setText(status);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rfidHandler.onDestroy();
    }

    public void handleTagdata(TagData[] tagData) {
        for (int index = 0; index < tagData.length; index++) {
            if (tagData[index].getMemoryBankData() != null) {
//                去重
                dataMap.put(tagData[index].getMemoryBankData(), tagData[index]);
            }
        }
    }

    public void handleTriggerPress(boolean pressed) {
        if (pressed) {
            runOnUiThread(() -> {
                dataMap.clear();//great清空map
            });
            rfidHandler.performInventory();
        } else {
            rfidHandler.stopInventory();
//            把显示放到这里不会重复显示
            runOnUiThread(() -> {
                for (Map.Entry<String, TagData> entry : dataMap.entrySet()) {
//                    显示要被写的标签号
                    editText2Tag.setText(entry.getValue().getTagID());
                }
            });
        }
    }

    //    写标签
    public void writeTag(View view) {
//        要写入的目标标签
        String toTag = editText2Tag.getText().toString();
//        要写入的编码，需要补全24位
        String writeData = editTextWriteData.getText().toString();
        if (toTag.length() == 0 || writeData.length() == 0) {
//            textView_tips.setText("请选择写入内容并读取单个标签");
            Toast.makeText(this, "请选择写入内容并读取单个标签", Toast.LENGTH_SHORT).show();
        } else {
            //左侧补齐 第一个参数：原始字符串，第二个参数：字符串的长度，第三个是补充的字符串
//            writeData = StringUtils.leftPad(writeData, 24, "A");
            rfidHandler.writeTag(toTag, writeData);
        }
    }

//    物资编码模糊搜索
    public void m_search(View view) {
        //得到用户输入的信息,进行非空判断
        String m_Name = editTextMName.getText().toString().trim();
        String m_ClassifyNum = editTextMClassifyNum.getText().toString().trim();
        String m_Specs = editTextMSpecs.getText().toString().trim();

        if (TextUtils.isEmpty(m_Name) && TextUtils.isEmpty(m_ClassifyNum) && TextUtils.isEmpty(m_Specs)) {
            Toast.makeText(this, "不能输入为空", Toast.LENGTH_SHORT).show();
            return;
        } else {
            list.clear();
            OkHttpClient client = new OkHttpClient();
            formBody = new FormBody.Builder()
                    .add("name", m_Name).add("classify_num", m_ClassifyNum).add("specs", m_Specs)
                    .build();
            //获取数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Request request = new Request.Builder().post(formBody).url(app.path_fuzzy_search).build();
                    try {
                        Response response = client.newCall(request).execute();
                        data = response.body().string();
                        //解析
                        if (data != null) {
                            try {
                                JSONArray array = new JSONArray(data);
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject object = array.getJSONObject(i);

                                    id = object.getInt("id");
                                    name = object.getString("name");
                                    classify_num = object.getString("classify_num");
                                    specs = object.getString("specs");
                                    unit = object.getString("unit");
                                    epc = object.getString("epc");

                                    Map<String, Object> map = new HashMap<>();
                                    map.put("id", id);
                                    map.put("name", name);
                                    map.put("classify_num", classify_num);
                                    map.put("specs", specs);
                                    map.put("unit", unit);
                                    map.put("epc", epc);
                                    list.add(map);
                                }
                                Message msg = new Message();
                                msg.what = 1;
                                handler.sendMessage(msg);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void addOrRemove(int position) {
        if (positionSet.contains(position)) {
            // 如果包含，则撤销选择
            positionSet.remove(position);
        } else {
            // 如果不包含，则添加
            positionSet.add(position);
        }
        if (positionSet.size() == 0) {
            // 如果没有选中任何的item，则退出多选模式
            recy_item_classify_adapter.notifyDataSetChanged();
            selectMode = false;
        } else {
            // 更新列表界面，否则无法显示已选的item
            recy_item_classify_adapter.notifyDataSetChanged();
        }
    }
}